import express from 'express';
import axios from 'axios';

const router = express.Router();

// 管理端API基础URL
const ADMIN_API_BASE = 'http://localhost:3000/api';

// 提交博客订阅
router.post('/subscribe', async (req, res) => {
    try {
        const { name, email, phone, subject, message, subscription_type = 'blog' } = req.body;
        
        // 验证必填字段
        if (!name || !email || !message) {
            return res.status(400).json({
                success: false,
                message: '姓名、邮箱和留言内容为必填项'
            });
        }

        // 构建订阅数据
        const subscriptionData = {
            name,
            email,
            phone: phone || '',
            subject: subject || '博客订阅',
            message,
            subscription_type,
            source: 'user-client',
            status: 'pending',
            created_at: new Date().toISOString()
        };

        // 发送到管理端API
        const response = await axios.post(`${ADMIN_API_BASE}/messages/subscribe`, subscriptionData);
        
        if (response.data.success) {
            res.json({
                success: true,
                message: '订阅成功！我们会尽快与您联系。',
                data: response.data.data
            });
        } else {
            res.status(500).json({
                success: false,
                message: response.data.message || '订阅失败，请稍后重试'
            });
        }
        
    } catch (error) {
        console.error('博客订阅失败:', error);
        
        // 如果管理端API不可用，保存到本地数据库作为fallback
        try {
            // 这里可以添加本地数据库保存逻辑
            console.log('订阅数据（管理端API不可用）:', {
                name: req.body.name,
                email: req.body.email,
                phone: req.body.phone,
                message: req.body.message
            });
            
            res.json({
                success: true,
                message: '订阅已提交！我们会尽快与您联系。',
                data: { id: Date.now(), status: 'pending' }
            });
        } catch (fallbackError) {
            res.status(500).json({
                success: false,
                message: '订阅失败，请稍后重试'
            });
        }
    }
});

// 获取订阅状态
router.get('/subscription/:email', async (req, res) => {
    try {
        const { email } = req.params;
        
        const response = await axios.get(`${ADMIN_API_BASE}/messages/subscriptions/${email}`);
        
        if (response.data.success) {
            res.json({
                success: true,
                data: response.data.data
            });
        } else {
            res.json({
                success: false,
                message: '未找到订阅信息'
            });
        }
        
    } catch (error) {
        console.error('获取订阅状态失败:', error);
        res.json({
            success: false,
            message: '获取订阅状态失败'
        });
    }
});

export default router;